#include "openmove_Prefix.h"
#include "NetBase.h"
#include "hawkthreads.h"

#ifdef __USE_WIN32THREAD__
CRITICAL_SECTION CNetBase::m_QueueReadSection;
#endif

CNetBase :: CNetBase(COgreEngine *pEngine) : m_IsReady(false), m_Shutdown(false), m_pEngine(pEngine), m_NetID(-1)
{	
}

CNetBase :: ~CNetBase(void)
{
}

void CNetBase :: Destroy(void)
{
	m_Shutdown = true;

#ifdef __USE_HAWKTHREAD__
	htMutexDestroy(&m_QueueReadMutex);
#endif
#ifdef __USE_WIN32THREAD__
	DeleteCriticalSection(&m_QueueReadSection);
#endif

#ifdef __USE_HAWKTHREAD__
	htThreadSleep(1);
#endif
#ifdef __USE_WIN32THREAD__
	Sleep(1);
#endif

	nlClose(m_Socket);
	nlShutdown();
}

void CNetBase :: Create(void)
{
	nlInit();
	nlSelectNetwork(NL_IP);

	m_Shutdown = false;
	m_IsReady = false;

#ifdef __USE_HAWKTHREAD__
	htMutexInit(&m_QueueReadMutex);
#endif
#ifdef __USE_WIN32THREAD__
	InitializeCriticalSection(&m_QueueReadSection);
#endif

	m_CommandQueue.clear();
}

void CNetBase :: WaitUntilReady(void)
{
	do
	{
#ifdef __USE_HAWKTHREAD__
		//htThreadSleep(0);
		htThreadYield();
#endif
#ifdef __USE_WIN32THREAD__
		Sleep(0);
#endif
	}
	while (!m_IsReady);
}

bool CNetBase :: frameStarted(const FrameEvent& evt)
{
	return (!m_Shutdown);
}

bool CNetBase :: SendPacket(NLsocket Peer, void *pBuffer, unsigned int Size)
{
	int WriteLen = nlWrite(Peer, pBuffer, Size);

	if (WriteLen != Size && WriteLen != NL_INVALID)
	{
		String Error = "HawkNL error:";
		Error += reinterpret_cast<char const *>(nlGetErrorStr(nlGetError()));
		Ogre::LogManager::getSingleton().logMessage("CNetBase::SendPacket: " + Error);

		return (false);
	}
	if (WriteLen == NL_INVALID)
	{
		return (false);
	}

	return (true);
}
